package com.fsz.pachong.pachong.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class WordUtil {
    private static Logger logger = LoggerFactory.getLogger(WordUtil.class);
    private static CloseableHttpClient httpClient = HttpClients.custom().build();
    public static String readWord(String url,String path,String fileName) {
        HttpGet httpGet = HttpClientConnectionManager.getGetMethod(url);
        File file = null;
        String buffer = "";
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            file = FileUtil.InputStreamFile(response.getEntity().getContent(), "utf-8",path,fileName);
            if(file != null) {
                if (fileName.endsWith(".doc")) {
                    InputStream is = new FileInputStream(file);
                    WordExtractor ex = new WordExtractor(is);
                    buffer = ex.getText();
                    ex.close();
                } else if (fileName.endsWith("docx")) {
                    OPCPackage opcPackage = POIXMLDocument.openPackage(file.getPath());
                    POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                    buffer = extractor.getText();
                    extractor.close();
                } else {
                    System.out.println("此文件不是word文件！");
                }
            }
            System.out.println(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer;
    }


    /**
     * 读取文档中表格
     * @param filePath 文档路径
     * @param orderNum 设置需要读取的第几个表格
     */
    public static String tableInWord(String filePath,Integer orderNum) {
        try {
            FileInputStream in = new FileInputStream(filePath);//载入文档
            // 处理docx格式 即office2007以后版本
            if (filePath.toLowerCase().endsWith("docx")) {
                //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
                XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
                Iterator<XWPFTable> itpre = xwpf.getTablesIterator();//得到word中的表格
                int total = 0;
                while (itpre.hasNext()) {
                    itpre.next();
                    total += 1;
                }
                Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
                // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
                int set = 0;
                if(orderNum > 0) {
                    set = orderNum;
                    // 过滤前面不需要的表格
                    for (int i = 0; i < set - 1; i++) {
                        it.hasNext();
                        it.next();
                    }
                }
//                List<List<String>> tableList = new ArrayList<>();
                StringBuffer message = new StringBuffer();
                while (it.hasNext()) {
                    XWPFTable table = it.next();
                    System.out.println("这是第" + (set+1) + "个表的数据");
                    List<XWPFTableRow> rows = table.getRows();
                    //读取每一行数据
                    for (int i = 0; i < rows.size(); i++) {
                        XWPFTableRow row = rows.get(i);
                        //读取每一列数据
                        List<XWPFTableCell> cells = row.getTableCells();
                        List<String> rowList = new ArrayList<>();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            rowList.add(cell.getText());
                            //输出当前的单元格的数据
                            System.out.print(cell.getText() + "[" + i + "," + j + "]" + "\t");
                            message.append(cell.getText()+"\t");
                        }
//                        tableList.add(rowList);
                        System.out.println();
                    }
                    // 过滤多余的表格
                    while (set > 0 && set < total) {
                        it.hasNext();
                        it.next();
                        set += 1;
                    }
                }
                return message.toString();
            } else {
                // 处理doc格式 即office2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(in);
                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator itpre = new TableIterator(range);
                //得到word中的表格
                int total = 0;
                while (itpre.hasNext()) {
                    itpre.next();
                    total += 1;
                }
                TableIterator it = new TableIterator(range);
                // 迭代文档中的表格
                // 如果有多个表格只读取需要的一个 set是设置需要读取的第几个表格，total是文件中表格的总数
                // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
                int set = 0;
                if(orderNum > 0) {
                    set = orderNum;
                    // 过滤前面不需要的表格
                    for (int i = 0; i < set - 1; i++) {
                        it.hasNext();
                        it.next();
                    }
                }
//                List<List<String>> tableList = new ArrayList<>();
                StringBuffer message = new StringBuffer();
                while (it.hasNext()) {
                    Table tb = (Table) it.next();
                    System.out.println("这是第" + (set+1) + "个表的数据");
                    //迭代行，默认从0开始,可以依据需要设置i的值,改变起始行数，也可设置读取到那行，只需修改循环的判断条件即可
                    for (int i = 0; i < tb.numRows(); i++) {
                        List<String> rowList = new ArrayList<>();
                        TableRow tr = tb.getRow(i);
                        //迭代列，默认从0开始
                        for (int j = 0; j < tr.numCells(); j++) {
                            TableCell td = tr.getCell(j);//取得单元格
                            //取得单元格的内容
                            for (int k = 0; k < td.numParagraphs(); k++) {
                                Paragraph para = td.getParagraph(k);
                                String s = para.text();
                                //去除后面的特殊符号
                                if (null != s && !"".equals(s)) {
                                    s = s.substring(0, s.length() - 1);
                                }
                                rowList.add(s);
                                System.out.print(s + "[" + i + "," + j + "]" + "\t");
                                message.append(s+"\t");
                            }
                        }
//                        tableList.add(rowList);
                        System.out.println();
                    }
                    // 过滤多余的表格
                    while (set > 0 && set < total) {
                        it.hasNext();
                        it.next();
                        set += 1;
                    }
                }
                return message.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void testWord(String filePath){
        try{
            FileInputStream in = new FileInputStream(filePath);//载入文档 //如果是office2007  docx格式
            if(filePath.toLowerCase().endsWith("docx")){
                //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
                XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
//             List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();//得到段落信息
                Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格

                while(it.hasNext()){

                    XWPFTable table = it.next();
                    List<XWPFTableRow> rows=table.getRows();
                    //读取每一行数据
                    for (int i = 1; i < rows.size(); i++) {
                        XWPFTableRow  row = rows.get(i);
                        //读取每一列数据
                        List<XWPFTableCell> cells = row.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell=cells.get(j);
                            //输出当前的单元格的数据
                            System.out.println(cell.getText());
                        }
                    }
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//		String content = tp.readWord("D:\\20180807.doc");
//        String content = readWord("https://fuwu.most.gov.cn/u/cms/zwpt/201907/10143817ym2x.doc","D:/test","test.doc");
//        System.out.println("content===="+content);
        testWord("D:/test/test.docx");
    }

}